package com.dwjm.controller;

import java.io.IOException;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.dwjm.entity.ActiveAccount;
import com.dwjm.entity.LoginLog;
import com.dwjm.entity.SitesCollection;
import com.dwjm.entity.SysUsers;
import com.dwjm.entity.User;
import com.dwjm.service.ActiveAccountService;
import com.dwjm.service.LoginLogService;
import com.dwjm.service.SitesCollectionService;
import com.dwjm.service.SysUsersService;
import com.dwjm.service.UserService;
import com.dwjm.util.EncryptUtil;
import com.dwjm.util.Md5Encrypt;
import com.dwjm.util.mail.MailUtil;
import com.dwjm.util.mail.MimeMessageDTO;

/**
 * @Description 用户登录Controller 
 * @author luans
 * @date 2016年12月19日
 * 
 */
@Controller
@RequestMapping("login")
public class LoginController {

	@Resource
	private SysUsersService sysUsersService;
	@Resource
	private ActiveAccountService activeAccountService;
	@Resource
	private LoginLogService loginLogService;
	@Resource
	private SitesCollectionService sitesCollectionService;
	@Resource
	private UserService userService;

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, false));
	}

	/**
	 * 
	 * @Description 后台：跳往登录页面
	 * @return ModelAndView
	 * @author luans
	 * @date 2016年12月19日
	 */
	@RequestMapping("beforelogin")
	public ModelAndView beforeLogin() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("manager/system/login");
		return mv;
	}

	/**
	 * @Description 后台：登录验证
	 * @throws Exception
	 * @author luans
	 * @date 2016年12月19日
	 * 
	 */
	@RequestMapping("backlogin")
	public String login(SysUsers user, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String URLStr = null;
		// 防止直接通过url访问
		if (user.getUserType() == 1) {
			request.setAttribute("userType", user.getUserType());
		} else {
			request.setAttribute("user", user);
			return "manager/system/login";
		}
		HttpSession session = request.getSession();
		// 从session中获取验证码
		String v_code = (String) session.getAttribute("validateCode");
		// 从请求中拿到前台提交的验证码
		String valiCode = request.getParameter("validateCode");
		if (!v_code.equalsIgnoreCase(valiCode.trim())) {
			request.setAttribute("msg", "验证码错误");
			request.setAttribute("user", user);
			return "manager/system/login";
		}
		// 根据用户名密码验证
		boolean check = pwdByName(user.getSysuserName(), user.getSysuserPwd());
		if (check) {
			// 获取管理员登录的信息
			SysUsers sysuser = sysUsersService.getPwdByName(user
					.getSysuserName());
			if (sysuser != null) {
				// 获取系统管理员登录跳转路径
				String loginRedirect = "system/index";
				session.setAttribute("back_user", sysuser);
				String value = this.setCookievalue(sysuser);
				Cookie cookie1 = new Cookie("back_user_cookie", value);
				cookie1.setMaxAge(60 * 60 * 24 * 1);// 设置Cookie的有效时间为1天
				cookie1.setPath("/");// cookie有效路径是网站根目录
				response.addCookie(cookie1); // 向客户端写入

				// 上次登录时间和IP
				LoginLog log = new LoginLog();
				List<LoginLog> list = loginLogService.selectListByUid(sysuser
						.getSysuserId());
				if (list.size() > 0) {
					log = list.get(0);
				} else {
					log = new LoginLog();
				}

				LoginLog login = new LoginLog();// 记录登录信息
				login.setLoginTime(new Date());
				login.setLoginType(1);// 类型 1:管理员；2:普通用户
				login.setLoginUid(sysuser.getSysuserId());
				System.out.println("客户端ip地址：" + this.getIpAddr(request));
				login.setLoginIp(this.getIpAddr(request));
				try {
					loginLogService.insertSelective(login);
				} catch (Exception e) {
					System.out.println("后台插入登录日志信息失败：" + user.getSysuserName());
				}
				session.setAttribute("login", log);
				URLStr = "redirect:/login/index.htm?loginRedirect="
						+ loginRedirect;
				// return redirect(loginRedirect);
			}
		} else {
			request.setAttribute("msg", "用户名称或密码错误");
			URLStr = "manager/system/login";
		}
		request.setAttribute("user", user);
		return URLStr;
	}

	/**
	 * @Description 后台：封装的校验用户名密码
	 * 
	 * @param name
	 *            用户名
	 * @param pwd
	 *            密码
	 * @return false,true
	 * @author luans
	 * @date 2016年12月19日
	 */
	public Boolean pwdByName(String name, String pwd) {
		boolean flag = false;
		SysUsers user = sysUsersService.getPwdByName(name);
		if (user == null) {
			return flag;
		}
		String str = user.getSysuserPwd();
		String code = str.substring(str.length() - 8, str.length());// 后8位
		String pwdcode = Md5Encrypt.md5(pwd + code);// 密码+后8位随机数 进行md5加密
		if (str.equals(pwdcode + code)) {
			flag = true;
		}
		return flag;
	}

	/**
	 * @Description 后台：用户信息加密写入Cookie的值
	 * 
	 * @param user
	 * @return String
	 * @throws Exception
	 * @date 2016年12月19日
	 * @auther luans
	 */
	@SuppressWarnings("static-access")
	public String setCookievalue(SysUsers user) throws Exception {

		EncryptUtil encryptUtil = new EncryptUtil();
		String value = encryptUtil.base64Encoder(user.getSysuserId() + ";"
				+ user.getSysuserName() + ";" + user.getSysuserPwd() + ";"
				+ "1");// 用base64加密;最后加的“1”，标记是管理员登录
		return value = URLEncoder.encode(value, "utf-8");// 编码格式
	}

	/**
	 * @Description 后台：去修改管理员密码页面
	 * 
	 * @param SysUsers
	 * @return ModelAndView
	 * @date 2016年12月19日
	 * @auther luans
	 */
	@RequestMapping("toupdatpwd")
	public ModelAndView toUpdatePwd(SysUsers user) {
		ModelAndView mv = new ModelAndView();
		if (user == null || user.getSysuserName() == null
				|| "".equals(user.getSysuserName())) {
			return beforeLogin();
		}
		mv.setViewName("manager/system/updatePwd");
		return mv;
	}

	/**
	 * @Description 后台：修改管理员密码
	 * 
	 * @param SysUsers
	 *            :（sysuserId，sysuserPwd）
	 * @return map(state状态：0失败；1成功，value:原因)
	 * @date 2016年12月19日
	 * @auther luans
	 */
	@RequestMapping("updatpwd")
	@ResponseBody
	public Map<Object, Object> updatePwd(SysUsers user) {
		Map<Object, Object> map = new HashMap<Object, Object>();
		if (user == null || user.getSysuserId() == null
				|| user.getSysuserId() <= 0) {
			map.put("state", 0);
			map.put("value", "参数错误");
			return map;
		}
		// 验证原密码
		SysUsers u = sysUsersService.selectByPrimaryKey(user.getSysuserId());
		String oldpwd = u.getSysuserPwd();
		String oldcode = oldpwd.substring(oldpwd.length() - 8, oldpwd.length());
		String checkpwd = Md5Encrypt.md5(user.getOldpwd() + oldcode) + oldcode;
		if (!u.getSysuserPwd().equals(checkpwd)) {
			map.put("state", 0);
			map.put("value", "原密码不正确");
			return map;
		}
		// 保存新密码
		String pwdcode = RandomStringUtils.randomAlphanumeric(8);// 生成8位随机字符串
		String pwd = Md5Encrypt.md5(user.getSysuserPwd() + pwdcode) + pwdcode;
		user.setSysuserPwd(pwd);
		int result = sysUsersService.updateByPrimaryKey(user);
		if (result == 1) {
			map.put("state", 1);
			map.put("value", "修改成功");
			return map;
		}
		return map;
	}

	/**
	 * 首页mian显示内容
	 * 
	 * @param request
	 * @return
	 * @author luans
	 * @data 2016年12月15日
	 */
	@RequestMapping("firstpage")
	public String firstPage(HttpServletRequest request) {

		Map<Object, Object> objMap = new HashMap<Object, Object>();
		Properties props = System.getProperties(); // 系统属性
		// 系统信息
		objMap.put("JAVA_VERSION", props.getProperty("java.version"));// jdk版本
		objMap.put("OS_NAME", props.getProperty("os.name"));// 系统
		objMap.put("mysqlProductName", "Mysql 5.6");// 数据库的产品名称

		request.setAttribute("objMap", objMap);

		return "manager/system/firstPage";
	}

	/**
	 * @Description PC端：跳转到登录注册页面
	 * 
	 * @return ModelAndView
	 * @author luans
	 * @date 2016年12月19日
	 */
	/*
	 * @RequestMapping("login") public ModelAndView gotoIndexPC() { ModelAndView
	 * mv = new ModelAndView(); mv.setViewName("/pc/login/login"); return mv; }
	 */

	/**
	 * @Description PC端：登录注册验证操作
	 * 
	 * @param HttpServletRequest
	 * @param HttpServletResponse
	 * @param User
	 * @throws Exception
	 * @author luans
	 * @date 2016年12月19日
	 */
	@RequestMapping("registerpc")
	@ResponseBody
	public Map<Object, Object> loginDesignPC(HttpServletRequest request,
			HttpServletResponse response, User user) throws Exception {
		Map<Object, Object> map = new HashMap<Object, Object>();
		// 验证参数
		if (user == null || user.getMarkerType() == null
				|| user.getEmail() == null || user.getPwd() == null) {
			map.put("state", 0);
			map.put("value", "参数错误");
			map.put("type", 1);
			return map;
		}
		HttpSession session = request.getSession();
		User sel_user = new User();
		String value = "";
		if (user.getMarkerType() == 1) {// 登录
			sel_user = userService.getPwdByName(user.getEmail());
			if (sel_user == null || sel_user.getEmail() == null) {
				map.put("state", 0);
				map.put("value", "邮箱不存在");
				map.put("type", 1);
				return map;
			} else {
				// 判断用户是否收藏网站
				List<SitesCollection> list = sitesCollectionService
						.selectByPrimaryKey(sel_user.getUid());
				Integer pc_colid = 0;
				if (list.size() > 0) {
					pc_colid = list.get(0).getColId();
				}
				sel_user.setPccolid(pc_colid);
				boolean pass = pwdByNamePC(user.getEmail(), user.getPwd());
				if (pass) {// 验证通过
					map.put("state", 1);
					map.put("value", "验证通过，登录成功");

					session.setAttribute("pc_user", sel_user);// 将用户信息存入Session
					session.setAttribute("pc_userid", sel_user.getUid());// 将用户ID存入Session

					// 写入Cookie
					value = this.setCookievalue(sel_user);
					Cookie cookie = new Cookie("pc_user_cookie", value);
					if (user.getRememberPwd() == 1) {// 记住密码
						cookie.setMaxAge(60 * 60 * 24 * 7);// 设置Cookie的有效时间为7天
					} else {// 不记住密码
						cookie.setMaxAge(60 * 60 * 24 * 1);// 设置Cookie的有效时间为1天
					}
					cookie.setPath("/");// cookie有效路径是网站根目录
					response.addCookie(cookie); // 向客户端写入
				} else {
					map.put("state", 0);
					map.put("value", "密码不正确");
					map.put("type", 2);
					// session.setAttribute("mj_password", "");
				}

			}
		} else if (user.getMarkerType() == 2) {// 注册
			String pwdcode = RandomStringUtils.randomAlphanumeric(8);// 生成8位随机字符串
			String code = RandomStringUtils.randomAlphanumeric(10);// 生成10位随机字符串

			String marker_jsp = (String) session.getAttribute("marker_jsp");
			// 邮箱注册
			map = registerUserByEmail(user.getEmail(), user.getPwd(), pwdcode,
					code, marker_jsp);

		}

		return map;
	}

	/**
	 * @Description PC端：封装的校验用户名密码
	 * 
	 * @param name
	 *            用户名
	 * @param pwd
	 *            密码
	 * @return false,true
	 * @author luans
	 * @date 2016年12月19日
	 */
	public Boolean pwdByNamePC(String name, String pwd) {
		boolean flag = false;
		User user = userService.getPwdByName(name);
		if (user == null || user.getPwd() == null) {
			return flag;
		}
		String str = user.getPwd();
		String code = str.substring(str.length() - 8, str.length());// 后8位
		String pwdcode = Md5Encrypt.md5(pwd + code);// 密码+后8位随机数 进行md5加密
		if (str.equals(pwdcode + code)) {
			flag = true;
		}
		return flag;
	}

	/**
	 * @Description PC端：用户信息加密写入Cookie的值
	 * 
	 * @param user
	 * @return String
	 * @throws Exception
	 * @date 2016年12月19日
	 * @auther luans
	 */
	@SuppressWarnings("static-access")
	public String setCookievalue(User user) throws Exception {

		EncryptUtil encryptUtil = new EncryptUtil();
		String value = encryptUtil.base64Encoder(user.getUid() + ";"
				+ user.getEmail() + ";" + user.getPwd() + ";" + "2" + ";"
				+ user.getPccolid());// 用base64加密;最后加的“2”，标记是PC端用户登录
		return value = URLEncoder.encode(value, "utf-8");// 编码格式
	}

	/**
	 * @Description PC端：邮箱注册激活
	 * 
	 * @param HttpServletRequest
	 * @param ModelAndView
	 * @return ModelAndView
	 * @author luans
	 * @date 2016年12月19日
	 */
	@RequestMapping("activeaccount")
	public ModelAndView activeAccount(HttpServletRequest request,
			HttpServletResponse response, ActiveAccount avtiveAccount) {
		ModelAndView mv = new ModelAndView();
		User user = new User();
		try {
			List<ActiveAccount> list = activeAccountService.queryActiveAccountByself(avtiveAccount);
			int result = 0;
			ActiveAccount queryModel = new ActiveAccount();
			if (list.size() != 1) {
				// 激活失败
				mv.setViewName("pc/error/error3");
			} else {
				queryModel = list.get(0);
				// 删除激活成功的数据
				result = activeAccountService.deleteActiveAccount(queryModel);
				user.setEmail(queryModel.getAaName());
				user.setPwd(queryModel.getAaPwd());
				//user.setUsername(queryModel.getAaName());
				result = userService.insertSelective(user);

			}
			if (result == 1) {// 激活成功
				if (queryModel.getAaUrl() == null
						|| "".equals(queryModel.getAaUrl())) {
					// mv.addObject("urlPath","http://szjyb.uibe.edu.cn/forumsystem/newsctr/forum.htm");
					mv.addObject("urlPath","http://101.201.146.100:8080/forumsystem/newsctr/forum.htm");
				} else {

					mv.addObject("urlPath", queryModel.getAaUrl());
				}
				HttpSession session = request.getSession();
				session.setAttribute("pc_user", user);
				session.setAttribute("pc_userid", user.getUid());
				mv.setViewName("pc/login/success_openEmail");
			} else {// 激活失败
				mv.setViewName("pc/error/error3");

			}
		} catch (Exception e) {
			System.out.println("PC端：邮箱注册激活error");
			// 跳转到连接失效页面
			mv.setViewName("pc/error/error3");
		}
		return mv;
	}

	/**
	 * 邮箱注册
	 * 
	 * @param username
	 *            :注册邮箱
	 * @param password
	 *            :密码
	 * @param pwdcode
	 *            :8位密码随机数
	 * @param code
	 *            :10位激活码随机数
	 * @return Map
	 * @date 2016年12月20日
	 * @auther luans
	 */
	public Map<Object, Object> registerUserByEmail(String username,
			String password, String pwdcode, String code, String marker_jsp) {
		Map<Object, Object> map = new HashMap<Object, Object>();
		ActiveAccount aa = new ActiveAccount();// 注册码表
		aa.setAaName(username);
		aa.setAaActivecode(code);
		aa.setAaUrl(marker_jsp);
		String pwdfinal = Md5Encrypt.md5(password + pwdcode) + pwdcode;
		aa.setAaPwd(pwdfinal);
		aa.setAaDate(new Date());
		activeAccountService.insertSelective(aa);
		// 设置邮件内容
		// String urlPath =
		// "http://szjyb.uibe.edu.cn/forumsystem/login/activeaccount.htm?aaId="+
		// aa.getAaId() + "&aaActivecode=" + code;
		String urlPath = "http://101.201.146.100:8080/forumsystem/login/activeaccount.htm?aaId="
				+ aa.getAaId() + "&aaActivecode=" + code;
		MimeMessageDTO mimeDTO = new MimeMessageDTO();
		String url = "欢迎您注册中国国际话语体系建设论坛账号，快快点击链接，完成最后的注册验证吧！" + urlPath;
		mimeDTO.setSentDate(new Date());
		mimeDTO.setSubject("中国国际话语体系建设论坛账号注册激链接邮件");
		mimeDTO.setText(url);

		// 设置相关参数
		String name = "dwjm_forum@163.com";// 发件人邮箱
		String pwd = "dwjm123";// 发件人邮箱密码
		String targetAddress = username;// 收件人邮箱

		// 发送邮件
		if (MailUtil.sendEmail(name, pwd, targetAddress, mimeDTO)) {
			map.put("state", 1);
			map.put("value", "注册邮箱发送成功，请到注册邮箱内点击链接完成注册验证！");
			map.put("email", username);
		} else {
			map.put("state", 0);
			map.put("value", "邮箱注册失败");
		}
		return map;
	}

	/**
	 * @Description PC端：去邮件发送成功页面
	 * 
	 * @param emailCount
	 *            :邮箱账户
	 * @return ModelAndView
	 * @author luans
	 * @date 2016年12月19日
	 */
	@RequestMapping("toemailcount")
	public ModelAndView gotoEmailCount(String emailcount) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("emailCount", emailcount);
		mv.setViewName("pc/login/success_sendEmail");
		return mv;
	}

	/**
	 * @Description PC端：退出登录
	 * 
	 * @return ModelAndView
	 * @throws IOException
	 * @author luans
	 * @date 2016年12月19日
	 */
	@RequestMapping("pcloginout")
	public void loginOutPC(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		// 1.1清除session
		request.getSession().invalidate();
		// 1.2清除cookie
		Cookie cookie = new Cookie("pc_user_cookie", null);
		cookie.setMaxAge(0);
		cookie.setPath("/");// cookie有效路径是网站根目录
		response.addCookie(cookie); // 向客户端写入
		response.sendRedirect(request.getContextPath() + "/newsctr/forum.htm");

	}

	/**
	 * @Description PC端：找回邮箱密码1:跳转到邮箱找回密码页
	 * 
	 * @return ModelAndView
	 * @author luans
	 * @date 2016年12月19日
	 */
	@RequestMapping("tobackpwd")
	public ModelAndView gotobackPwd() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/pc/login/backpwd1");
		return mv;
	}

	/**
	 * @Description PC端：找回邮箱密码2.1:发送链接到指定邮箱
	 * 
	 * @param emailCount
	 *            ：邮箱
	 * @return ModelAndView
	 * @author luans
	 * @date 2016年12月19日
	 */
	@RequestMapping("backpwd")
	public ModelAndView backPwd(HttpServletRequest request,
			HttpServletResponse response, String emailcount) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("emailCount", emailcount);
		User user = userService.getPwdByName(emailcount);
		String code = RandomStringUtils.randomAlphanumeric(10);// 生成10位随机字符串
		ActiveAccount aa = new ActiveAccount();// 注册码表
		aa.setAaName(emailcount);// 找回密码的邮箱
		aa.setAaActivecode(code);// 激活码
		aa.setAaDate(new Date());// 添加时间
		activeAccountService.insertSelective(aa);
		// 设置邮件内容
		// String urlPath =
		// "http://szjyb.uibe.edu.cn/forumsystem/login/toresetpwd.htm?uid="+
		// user.getUid()+"&aaId="+ aa.getAaId()+ "&aaActivecode="+
		// aa.getAaActivecode();
		String urlPath = "http://101.201.146.100:8080/forumsystem/login/toresetpwd.htm?uid="
				+ user.getUid()
				+ "&aaId="
				+ aa.getAaId()
				+ "&aaActivecode="
				+ aa.getAaActivecode();
		MimeMessageDTO mimeDTO = new MimeMessageDTO();
		String url = "还差一点点就能找回密码了，赶快点击链接，重置密码吧！" + urlPath;
		mimeDTO.setSentDate(new Date());
		mimeDTO.setSubject("中国国际话语体系建设论坛邮箱账号找回密码邮件");
		mimeDTO.setText(url);

		// 设置相关参数
		String name = "dwjm_forum@163.com";// 发件人邮箱
		String pwd = "dwjm123";// 发件人邮箱密码
		String targetAddress = emailcount;// 收件人邮箱

		// 发送邮件
		if (MailUtil.sendEmail(name, pwd, targetAddress, mimeDTO)) {
			mv.setViewName("pc/login/backpwd2");
		} else {
			// 重定向的首页：
			try {
				response.sendRedirect(request.getContextPath()
						+ "/newsctr/forum.htm");
			} catch (IOException e) {
				System.out.println("找回密码重定向失败");
			}
		}

		return mv;
	}

	/**
	 * @Description PC端：找回邮箱密码2.2:通过邮箱链接跳转到重置密码页面
	 * 
	 * @param HttpServletRequest
	 * @param ModelAndView
	 * @return ModelAndView
	 * @author luans
	 * @date 2016年12月19日
	 */
	@RequestMapping("toresetpwd")
	public ModelAndView gotoResetPwd(HttpServletRequest request,
			HttpServletResponse response, String uid, ActiveAccount aa) {
		ModelAndView mv = new ModelAndView();
		try {
			List<ActiveAccount> list = activeAccountService.queryActiveAccountByself(aa);
			if (list.size() != 1) {
				// 激活失败:链接失效
				System.out.println("找回邮箱密码2.21:通过邮箱链接跳转到重置密码页面重定向失败");
				mv.setViewName("pc/error/error1");

			} else {
				// 删除激活成功的数据
				activeAccountService.deleteActiveAccount(list.get(0));
				mv.addObject("uid", uid);
				mv.setViewName("pc/login/backpwd3");
			}
		} catch (Exception e) {
			System.out.println("找回邮箱密码2.2:通过邮箱链接跳转到重置密码页面重定向失败");
			// 跳转到连接失效页面
			mv.setViewName("pc/error/error1");
		}
		return mv;
	}

	/**
	 * @Description PC端：找回邮箱密码3:重置密码
	 * 
	 * @param HttpServletRequest
	 * @param ModelAndView
	 * @return ModelAndView
	 * @author luans
	 * @date 2016年12月19日
	 */
	@RequestMapping("resetpwd")
	public ModelAndView resetPwd(HttpServletRequest request,
			HttpServletResponse response, Integer uid, String pwd) {
		ModelAndView mv = new ModelAndView();
		try {
			if (uid == null || uid <= 0) {
				// 重定向的首页：
				mv.setViewName("pc/error/error2");
				return mv;
			}
			String pwdcode = RandomStringUtils.randomAlphanumeric(8);// 生成8位随机字符串
			String password = Md5Encrypt.md5(pwd + pwdcode) + pwdcode;
			User user = new User();
			user.setUid(uid);
			user.setPwd(password);
			int result = userService.userUpdate(user);
			if (result == 0) {
				// 重定向的首页：
				mv.setViewName("pc/error/error2");
				return mv;
			} else {

				user = userService.selectByPrimaryKey(user);
				HttpSession session = request.getSession();
				session.setAttribute("mj_username", user.getEmail());
				mv.addObject("uid", user.getEmail());
				mv.setViewName("pc/login/backpwd4");
			}
		} catch (Exception e) {
			// 重定向的首页：
			mv.setViewName("pc/error/error2");
		}

		return mv;
	}

	/**
	 * 获取客户端IP地址
	 * 
	 * @param request
	 * @return String
	 * @date 2016年12月19日
	 * @author luans
	 */
	private String getIpAddr(HttpServletRequest request) {
		String ipAddress = null;
		// ipAddress = this.getRequest().getRemoteAddr();
		ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			if (ipAddress.equals("127.0.0.1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ipAddress = inet.getHostAddress();
			}

		}

		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
															// = 15
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}

	/**
	 * @Description 管理员退出登录，需要消除session/cookie
	 * 
	 * @author luans
	 * @date 2016年12月19日
	 */
	@RequestMapping("logout")
	public String logout(HttpServletRequest request,
			HttpServletResponse response) {
		// 1.1清除session
		request.getSession().invalidate();
		// 1.2清除cookie
		Cookie cookie = new Cookie("back_user_cookie", null);
		cookie.setMaxAge(0);
		cookie.setPath("/");// cookie有效路径是网站根目录
		response.addCookie(cookie); // 向客户端写入
		// 2.跳转到登录界面
		return "manager/system/login";
	}

	/**
	 * @跳转到主界面
	 * @param loginRedirect
	 * @return
	 */
	@RequestMapping("/index")
	public String redirect(String loginRedirect) {
		return "manager/" + loginRedirect;
	}

	/**
	 * 验证注册的邮箱是否重复
	 * 
	 * @param HttpServletRequest
	 * @return Map
	 * @date 2016年12月29日
	 * @auther luans
	 */
	@RequestMapping("checksamename")
	@ResponseBody
	public Map<Object, Object> checkSameName(HttpServletRequest request) {
		Map<Object, Object> map = new HashMap<Object, Object>();
		String username = request.getParameter("pc_username");
		int result = userService.checkSameName(username);
		map.put("state", result);
		return map;
	}

}
